import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Table, Form, Input, Popconfirm,DatePicker, Select,TreeSelect, Row, Col ,Spin,message} from 'antd';

import AddModal from '../../components/asset/AddModal';
import {baseUrl} from '../../config/system'
import ExportDetailModal from '../../components/asset/ExportDetailModal';
import DownLoadDetailModal from '../../components/asset/DownLoadDetailModal';
const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const RangePicker = DatePicker.RangePicker;
var _this;

class Maintain extends Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        var dispatch = this.props.dispatch;
        var ws = new SockJS(baseUrl+"/message");
        ws.onopen = function () {
           console.log("onpen");
           ws.send("{}");
        }
        ws.onclose = function () {
            console.log("onclose");
            if(ws &&ws.readyState==3){
                ws = new SockJS(baseUrl+"/message");
            }
           
        }    
        ws.onmessage = function (msg) {
            console.log(msg+"msg");
            if(msg.data!="成功建立socket连接"){
                var data=eval("("+msg.data+")");
               console.log(eval("("+msg.data+")"));
                 if(data.timeStamp==_this.props.maintain.timeStemp){                     
                     console.log(_this.props.maintain.InterValObj+"TIMETIME");
                      window.clearTimeout(_this.props.maintain.InterValObj);//停止计时器
                     if(data.status==1){
                        dispatch({
                            type: 'maintain/queryListLight', 
                            search:{..._this.props.form.getFieldsValue(),...{'pageNum':_this.props.maintain.current, 'pageSize':_this.props.maintain.currentSize}},
                        })   
                        message.success("点亮成功");   
                     }else if(data.status==2){
                        dispatch({
                            type: 'maintain/queryListLight', 
                            search:{..._this.props.form.getFieldsValue(),...{'pageNum':_this.props.maintain.current, 'pageSize':_this.props.maintain.currentSize}},
                        })   
                        message.success("点灭成功");   
                     }else{
                        dispatch({
                            type: 'maintain/updateState', 
                            payload: { lightLoading:false },
                        })   
                        message.error("操作失败");                          
                     }                                  
                }
            }           
        }    
    }

    render() {
     _this = this; 
    const { getFieldDecorator, getFieldsValue, getFieldValue } =  this.props.form;
    const { modalVisible,importModalVisible,importModalVisible2, modalType,roomList,assetTypeTree,
        assetBrandList,rackList,assetModelList,existsSerialNo,attrValues,groupList,typeId,brandId,
        assetId,attrValuesForm,assetData,manageDeptTree,useDeptTree,userList,timeStemp,loading,lightLoading} =  this.props.maintain
    const maintain=this.props.maintain;
    var dispatch = this.props.dispatch;    
    const columns = [{
            title: '资产编号',
            dataIndex: 'assetNo',
            key: 'assetNo',
            width: 150,
        },{
            title: '设备序列号',
            dataIndex: 'serialNo',
            key: 'serialNo',
            width: 150,
        },{
            title: '资产分类',
            dataIndex: 'typeName',
            key: 'typeName',
            width: 100,
        },{
            title: '设备名称',
            dataIndex: 'assetName',
            key: 'assetName',
            width: 150,
        },{
            title: '品牌',
            dataIndex: 'brandName',
            key: 'brandName',
            width: 100,
        },{
            title: '设备型号',
            dataIndex: 'modelName',
            key: 'modelName',
            width: 120,
        },{
            title: 'RFID号',
            dataIndex: 'rfidNo',
            key: 'rfidNo',
            width: 100,
        },{
            title: 'IP地址',
            dataIndex: 'ip',
            key: 'ip',
            width: 120,
        },{
            title: '所在位置',
            dataIndex: 'roomName',
            key: 'roomName',
            width: 160,
        },{
            title: '所在机柜',
            dataIndex: 'rackName',
            key: 'rackName',
            width: 100,
        },{
            title: 'U位',
            dataIndex: 'startU',
            key: 'startU',
            width: 100,
            render: (value, row, index) => {
                var u;
                if(row.startU){
                    u =row.startU;
                    if(row.endU){
                        u= row.startU+'-'+row.endU;
                    }
                }
                return (
                    u
                )
            }
        },{
            title: '设备状态',
            dataIndex: 'statusName',
            key: 'statusName',
            width: 80
        },{
            title: '是否借用',
            dataIndex: 'isBorrow',
            key: 'isBorrow',
            width: 80,
            render: (value, row, index) => {
                return (
                    value == 1 ? "借用" : '未借用'
                )
            }
        },{
            title: '是否分配',
            dataIndex: 'isDistribute',
            key: 'isDistribute',
            width: 80,
            render: (value, row, index) => {
                return (
                    value == 1 ? "已分配" :'未分配'
                )
            }
        },{
            title: '管理部门',
            dataIndex: 'manageBranchName',
            key: 'manageBranchName',
            width: 150,
        },{
            title: '领用部门',
            dataIndex: 'branchName',
            key: 'branchName',
            width: 120,
        },{
            title: '领用人',
            dataIndex: 'endUserName',
            key: 'endUserName',
            width: 100,
        },{
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 120,
        }
        // ,{
        //     title: '点亮状态',
        //     dataIndex: 'isLight',
        //     key: 'isLight',
        //     width: 80,
        //     render: (value, row, index) => {
        //         return (
        //             value==1?"已点亮":"未点亮"
        //         )
        //     }
        // }
        ,{
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 60,
            render: (text, record) => (
                <span>
                <a onClick={onEditItem.bind(null, record.id_, record.typeId_,record.roomId_,record.brandId_,record.useBranchId_)}>配置</a>
                {/* {(record.status==2)? (record.isLight==1)?(
                    <span>
                        <span className="ant-divider" />
                        <a onClick={cancleLight.bind(null, record.id_,record.endU,record.rackConverCode)}>取消点亮</a>
                    </span>
               ):(
                <span>
                    <span className="ant-divider" />
                    <a onClick={onLight.bind(null, record.id_,record.endU,record.rackConverCode)}>点亮</a>
                </span>
               ):""} */}
                </span>
            ),
    }];
    const pagination = {
        current:maintain.current,
        pageSize:maintain.currentSize,
        total: maintain.total,
        showSizeChanger: true,
        showTotal: (total => '共' + maintain.total + '条'),
        onShowSizeChange(current, size) {
            dispatch({
                type: 'maintain/queryList',
                payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':size} },
            });
        },
        onChange(current) {
            dispatch({
                type: 'maintain/queryList',
                payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':maintain.currentSize} },
            });
        },
    };
    const editHandler = (id, values) => {
        dispatch({
            type: 'maintain/edit',
            payload: { id, ...values },
        });
    }
    const submitHandle = () => {
        dispatch({
            type: 'maintain/queryList',
            payload: { ...getFieldsValue() },
        });
    }
    const handleDownLoadExl = () => {
        let param = JSON.stringify({ ...getFieldsValue() });
        param = encodeURIComponent(param);
        window.open(baseUrl+"/asset/downLoadEXL?param="+param);
    }

    const handleExportExl=()=> {
      dispatch({
          type: 'maintain/showExcelModal',
      })
     }

    const handleDownLoadExlModel=()=> {
       dispatch({
           type: 'maintain/showDownLoadExcelModal',
       })
    }

    function handleClear(){
      _this.props.form.resetFields();
    }
    const onEditItem = (id,typeId,roomId,brandId,useBranchId) => {      
        dispatch({
            type: 'maintain/qryById',
            payload:{assetId:id,typeId:typeId,roomId:roomId,brandId:brandId,useBranchId:useBranchId},
        })
        dispatch({
            type: 'maintain/qryAttrValue',
            payload:{assetId:id,typeId:typeId,roomId:roomId,brandId:brandId},
        })
    }
    //点亮标签
    const onLight = (id,startU,rackConverCode) => {
        dispatch({
            type: 'maintain/onLight',
            payload:{assetId:id,startU:startU,rackConverCode:rackConverCode},
            search:{...getFieldsValue(),...{'pageNum':maintain.current, 'pageSize':maintain.currentSize}}
        })
        function setRemainTime() {
            window.clearTimeout(InterValObj);//停止计时器           
            message.error("操作失败");    
             dispatch({
                type: 'maintain/updateState',
                payload:{lightLoading:false},
            })    
        }  
        var InterValObj = window.setTimeout(setRemainTime, 30000); //启动计时器，1秒执行一次  
            dispatch({
                type: 'maintain/updateInterValObj',
                payload:{InterValObj:InterValObj},
            })  
         
    }
     //取消点亮标签
    const cancleLight = (id,startU,rackConverCode) => {
        dispatch({
            type: 'maintain/cancleLight',
            payload:{assetId:id,startU:startU,rackConverCode:rackConverCode},
            search:{...getFieldsValue(),...{'pageNum':maintain.current, 'pageSize':maintain.currentSize}}
        })
        function setRemainTime() {
            window.clearTimeout(InterValObj);//停止计时器           
            message.error("操作失败");    
             dispatch({
                type: 'maintain/updateState',
                payload:{lightLoading:false},
            })    
        }  
        var InterValObj = window.setTimeout(setRemainTime, 30000); //启动计时器，1秒执行一次  
            dispatch({
                type: 'maintain/updateInterValObj',
                payload:{InterValObj:InterValObj},
            })  
    }

    const roomChange= (data) => {
        this.props.form.setFieldsValue({rackId: undefined});
        dispatch({
            type: 'maintain/qrySearchRackList',
            payload: data,
        })
    }

    const modalDownLoadProps = {
            maskClosable: false,
            visible: importModalVisible2,
            assetType:assetTypeTree,
            dispatch: dispatch,
            title: '资产分类模板导出',
            wrapClassName: 'vertical-center-modal',
            newKey : maintain.newKey2,
            onOk () {
            },
            onCancel () {
              dispatch({
                  type: `maintain/hiddenDownLoadExcelModal`,
                  payload: {},
              })
            },
      }

    const modalExportProps = {
        maskClosable: false,
        visible: importModalVisible,
        dispatch: dispatch,
        title: '资产导入',
        wrapClassName: 'vertical-center-modal',
        newKey : maintain.newKey1,
        onOk () {
        },
        onCancel () {
            dispatch({
                type: `maintain/closeExcelModal`,
                payload: {},
            })
        },
    }

    const modalProps = {
        visible: modalVisible,
        type: modalType,
        dispatch:dispatch,
        assetId: assetId,
        brandId:brandId,
        typeId:typeId,
        existsSerialNo:existsSerialNo,
        roomList:roomList,
        userList:userList,
        manageDeptTree:manageDeptTree,
        useDeptTree:useDeptTree,
        assetType:assetTypeTree,
        assetBrandList:assetBrandList,
        assetModelList:assetModelList,
        rackList:rackList,
        groupList:groupList||[],
        attrValues:attrValues||[],
        attrValuesForm:attrValuesForm||{},
        assetData:assetData,
        maskClosable: false,
        title: '配置资产属性',
        wrapClassName: 'vertical-center-modal',
        newKey : maintain.newKey,
        onOk (data,reset) {
            dispatch({
                type: `maintain/${modalType}`,
                payload: data,
                resetFields: reset,
                search:{...getFieldsValue(),...{'pageNum':maintain.current, 'pageSize':maintain.currentSize}}
            })
        },
        onCancel () {
            dispatch({
                type: 'maintain/hideModal',
            })
        },
        checkSerialNo(data) {
            dispatch({
                type: 'maintain/checkSerialNo',
                payload: data,
            })
        },
        handleRoomChange (data) {
            dispatch({
                type: 'maintain/qryRackList',
                payload: data,
            })
        },
        handleBrandChange (data) {
            dispatch({
                type: 'maintain/queryAssetModel',
                payload: data,
            })
        },
    }

    const loopRoom = data => data.map((item) => {
      return <Option key={item.id_ + ''}>{item.name}</Option>
    });
    const loopBrand = data => data.map((item) => {
      return <Option key={item.id_ + ''}>{item.name}</Option>
    });
    const getRack = data => data.map((item) => {
        return <Option key={item.id_+''}>{item.assetName}</Option>
    })
    const treeData = (i) => {
        return i.map( d => {
          d.label = d.name;
          d.key = d.id_+'';
          d.value = d.id_+'';
          d.children = d.assetType && d.assetType.length > 0 ? treeData(d.assetType) : [];
          return d;
        })
    }

    const formItemLayout = {
        wrapperCol: { className: 'wrapper-col' },
    }

    return (
        <Spin spinning={lightLoading} >
        <div style={{backgroundColor:'#fff'}}>
          <div style={{minHeight:'100%'}}>
              <div style={{width:'100%',backgroundColor:'#fff',lineHeight:'40px',paddingLeft:'20px',paddingTop:'10px', paddingRight:'20px'}}>
                <Form layout="inline" style={{width:'100%'}}>
                  <Row gutter={16}>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('assetName')(<Input  placeholder="请输入设备名称模糊查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('rfidNo')(<Input  placeholder="请输入RFID查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('assetNo')(<Input  placeholder="请输入资产编号查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('serialNo')(<Input  placeholder="请输入资产序列号查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('roomId')(
                                <Select
                                    showSearch
                                    allowClear
                                    placeholder="选择机房/库房"
                                    optionFilterProp="children"
                                    onChange={roomChange}
                                    dropdownMatchSelectWidth={true}
                                    style={{ width: '100%' }}
                                >
                                <Option value="">全部</Option>
                                {loopRoom(maintain.roomList)}
                                </Select>
                                )
                            }
                            </FormItem>
                        </Col>           
                    </Row>
                    <Row gutter={16}>
                        <Col span={5}>
                          <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('rackId')(
                                <Select
                                    showSearch
                                    style={{ width:'100%' }}
                                    allowClear
                                    placeholder="请选择所在机柜"
                                >
                                 <Option value="">全部</Option>
                                  {getRack(maintain.searchRackList)}
                                </Select>
                                )
                            }
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('typeId')(
                                <TreeSelect
                                    style={{ width: '100%' }}
                                    showSearch
                                    treeNodeFilterProp="title"
                                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                    placeholder="请选择资产分类"
                                    allowClear
                                    treeDefaultExpandAll
                                    treeData={treeData(assetTypeTree)}
                                >
                              
                                </TreeSelect>
                                )
                            }
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {
                                getFieldDecorator('brandId')(
                                <Select
                                    showSearch
                                    style={{ width: '100%' }}
                                    placeholder="选择品牌"
                                    optionFilterProp="children"
                                >
                                 <Option value="">全部</Option>
                                {loopBrand(assetBrandList)}
                                </Select>
                                )
                            }
                            </FormItem>
                        </Col>
                        <Col span={5}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('status')(
                                <Select
                                    showSearch
                                    style={{ width: '100%' }}
                                    placeholder="选择状态"
                                    optionFilterProp="children"
                            >
                                <Option value="">全部</Option>
                                <Option value="1">已入库</Option>
                                <Option value="2">已上架</Option>
                                <Option value="3">已报废</Option>
                                <Option value="4">已出库</Option>

                                </Select>
                            )}
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <FormItem style={{ width: '100%' }} {...formItemLayout}>
                            {getFieldDecorator('ip')(<Input  placeholder="请输入IP查找" style={{ width: '100%' }}/>)}
                            </FormItem>
                        </Col>                         
                        </Row>
                        <Row gutter={16}>
                        <Col span={24} style={{ textAlign:'right',paddingRight:0}}>                        
                        <FormItem>
                        <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
                        </FormItem>
                        <FormItem>
                        <Button size="large" htmlType="reset" onClick={handleClear}>清空</Button>
                        </FormItem>
                        <FormItem>
                        <Button size="large" onClick={handleDownLoadExlModel}>导出分类模板</Button>
                        </FormItem>
                        <FormItem>
                        <Button size="large" onClick={handleDownLoadExl}>导出EXCEL</Button>
                        </FormItem>
                        <FormItem>
                        <Button size="large" onClick={handleExportExl}>导入EXCEL</Button>
                        </FormItem>

                        </Col>
                        </Row>
                      
                </Form>
            </div>
            <div style={{width:'100%',padding:"30px 20px",}}>
                <Table columns={columns} rowKey={record => record.id_} scroll={{ x: 2400 }} loading={loading} dataSource={maintain.list} pagination={pagination}
                />
            </div>
            </div>
               <AddModal {...modalProps} />
               <ExportDetailModal {...modalExportProps} />
               <DownLoadDetailModal {...modalDownLoadProps} />
        </div>
        </Spin>
    );
  }
}

function mapStateToProps(state) {
  return { maintain : state.maintain,loading:state.loading.models.maintain};
}

Maintain = Form.create()(Maintain);

export default connect(mapStateToProps)(Maintain);
